package com.xuecheng.gateway.filter;


import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class Authfilter  implements Ordered, GlobalFilter {
        @Autowired
       private RedisTemplate redisTemplate;
    //过滤拦截tokekn
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //放行部分url（有些请求不用登录也能访问）
        String path = request.getURI().getPath();
        if (path.contains("coursePub/preview") ||
                path.contains("auth/login") ||
                path.contains("basic/dictionary") ||
                path.contains("category/tree-nodes") ||
                path.contains("course/upload") ||
                path.contains("search/") ||
                path.contains("payment/wx/notify")) {
            return chain.filter(exchange);
        }
        //获取请求头中的token
        String token = request.getHeaders().getFirst("Authorization");
        //对token进行校验
        Boolean verifyToken = JwtUtils.verifyToken(token);
        if (verifyToken == false) {
            response.setRawStatusCode(401);//权限不足，直接跳转到登录页
            return response.setComplete();//直接拦截，并返回
        }
        //解析token
        AuthInfo authInfo = JwtUtils.getInfoFromToken(token);
        //判断token是否过期
        if (!redisTemplate.hasKey(UserConstants.USER_ID+authInfo.getUid())){
            response.setRawStatusCode(401);//权限不足，跳转到登录页
            return response.setComplete();//直接拦截并返回
        }
        //判断小于一小时，续期
        Long expire = redisTemplate.getExpire(UserConstants.USER_ID + authInfo.getUid(),
                TimeUnit.HOURS);
        if (expire<1){
            redisTemplate.expire(UserConstants.USER_ID+authInfo.getUid(),3,TimeUnit.HOURS);
        }
        //将authinfo转成json 设置到payload请求头，实现路由转发
        String json = JSON.toJSONString(authInfo);
        //解决中文乱码问题
        String encode = null;
        try {
            encode = URLEncoder.encode(json, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        ServerHttpRequest newRequest = request.mutate().header("payload", encode).build();
        //将newRequest设置到exchange
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        //放行
        return  chain.filter(newExchange);
    }
        @Override
    public int getOrder() {
        return 0;
    }
}
